/**
Copyright [2009] [Julian Gamble] 

Licensed under the Apache License, Version 2.0 (the "License"); 
you may not use this file except in compliance with the License. 
You may obtain a copy of the License at 

	http://www.apache.org/licenses/LICENSE-2.0 
	
Unless required by applicable law or agreed to in writing, software 
distributed under the License is distributed on an "AS IS" BASIS, 
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
See the License for the specific language governing permissions and 
limitations under the License. 
 **/
package cruiseprojectlist.service;

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Map;
import java.util.TreeMap;

import cruiseprojectlist.domain.ProjectPreference;
import cruiseprojectlist.domain.ProjectsStorageBucket;

public class ProjectStorageBucketService {

	private static final String PROJECT_PREFERENCES_XML = "ProjectPreferences.xml";

	public static void save(ProjectsStorageBucket projectsStorageBucket) {

		XMLEncoder e = null;
		try {
			e = new XMLEncoder(new BufferedOutputStream(new FileOutputStream(
					PROJECT_PREFERENCES_XML)));
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		}

		e.writeObject(projectsStorageBucket);
		e.close();

	}

	public static Map<String, ProjectPreference> getProjectPreferencesMap() {
		Map<String, ProjectPreference> projectPreferencesMap = null;

		if (new File(PROJECT_PREFERENCES_XML).exists()) {
			projectPreferencesMap = readProjectPreferences();
		} else {
			projectPreferencesMap = new TreeMap<String, ProjectPreference>();
		}

		return projectPreferencesMap;
	}

	private static Map<String, ProjectPreference> readProjectPreferences() {
		Map<String, ProjectPreference> projectPreferences;
		ProjectsStorageBucket projectsStorageBucket = getProjectsStorageBucket();
		projectPreferences = projectsStorageBucket.getProjectPreferences();

		return projectPreferences;
	}

	public static ProjectsStorageBucket getProjectsStorageBucket() {
		ProjectsStorageBucket projectsStorageBucket = new ProjectsStorageBucket();
		if (new File(PROJECT_PREFERENCES_XML).exists()) {
			XMLDecoder d = null;
			try {
				d = new XMLDecoder(new BufferedInputStream(new FileInputStream(
						PROJECT_PREFERENCES_XML)));
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
			Object objectReadResult = d.readObject();
			d.close();
			projectsStorageBucket = (ProjectsStorageBucket) objectReadResult;
		}

		return projectsStorageBucket;
	}

}
